<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta content="0" http-equiv="expires">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <title>hello, world!</title>
    <style>
        * {
            font-size: 24px;
        }

        body {
            margin-left: 50px;
        }

        .work {
            display: none;
        }

        #server {
            width: 400px;
        }
    </style>
</head>
<body>
<h1>websocket基础</h1>
<div>
    <input type="button" onclick="location.reload();" value="location.reload();"/>
    websocket server: <input id="server" value="ws://localhost:8080/websocket/"/><br/>
    nickname：<input id="nickname" value="bobydog"/><br/>
    <input type="button" id="btn_open" onclick="openWebsocket();" value="connect"/>
    <span class="work">
        <input type="button" id="btn_close" onclick="closeWebsocket();" value="close"/>
    </span>
    <br/>
    <span class="work">
        <input id="tosend" value="hello"/>
        <input type="button" onclick="sendmessage();" value="sendmessage"/>
    </span>
</div>
<div id="message"></div>
</body>
</html>
<!--注意引用的路径-->
<script src="../js/jquery.3.2.1.min.js"></script>
<script>
    let websocket = null;

    //将消息显示到某区域
    function appendMessage(s) {
        $('#message').append(`<br/>${new Date()}：${s}`);
    }

    //打开websocket连接
    function openWebsocket() {
        let wsUrl = $('#server').val() + $('#nickname').val();
        websocket = new WebSocket(wsUrl);
        websocket.onopen = function (evt) {//连接打开事件
            let s = "Connection open ...";
            appendMessage(s);
            $('#btn_open').hide();
            $('.work').show();
        };
        websocket.onmessage = function (evt) {//收到消息事件
            appendMessage(`Received Message: ${evt.data}`);
        };
        websocket.onclose = function (evt) {//连接关闭事件
            appendMessage(`Connection closed.`);
            $('#btn_open').show();
            $('.work').hide();
        };
    }

    //关闭连接
    function closeWebsocket() {
        websocket.close();
    }

    //发送消息
    function sendmessage() {
        websocket.send($('#tosend').val());
    }
</script>